<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->

<template>
  <div class="user">
    <basic-container>
      <avue-crud
        :option="multiple ? option : option2"
        ref="crud"
        v-model="form"
        :page="page"
        @on-load="getList"
        @size-change="sizeChange"
        @current-change="currentChange"
        :table-loading="listLoading"
        @search-change="handleFilter"
        @refresh-change="handleRefreshChange"
        @row-update="update"
        @row-save="create"
        :before-open="handleOpenBefore"
        :data="list"
      >
        <template slot="menuLeft">
          <el-button
            v-if="sys_user_add"
            class="filter-item"
            @click="$refs.crud.rowAdd()"
            type="primary"
            icon="el-icon-edit"
            >添加
          </el-button>
        </template>
        <template slot="username" slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
        <template slot="role" slot-scope="scope">
          <span v-for="(role, index) in scope.row.roleList" :key="index">
            <el-tag>{{ role.roleName }} </el-tag>&nbsp;&nbsp;
          </span>
        </template>
        <template slot="deptId" slot-scope="scope">
          {{ scope.row.deptName }}
        </template>
        <template slot="lockFlag" slot-scope="scope">
          <el-tag>{{ scope.label }}</el-tag>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
            v-if="sys_user_edit"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row, scope.index)"
            >编辑
          </el-button>
          <el-button
            v-if="sys_user_del"
            type="text"
            icon="el-icon-delete"
            @click="deletes(scope.row, scope.index)"
            >删除
          </el-button>
          <!-- <el-button
            v-if="multiple == false"
            type="text"
            @click="goPage(scope.row, scope.index)"
            >登录用户后台
          </el-button> -->
        </template>
        <template slot="deptIdForm" slot-scope="scope">
          <avue-input-tree
            v-model="form.deptId"
            placeholder="请选择所属部门"
            :node-click="getNodeData"
            :dic="treeDeptData"
            :props="defaultProps"
          ></avue-input-tree>
        </template>
        <template slot="roleForm" slot-scope="scope">
          <avue-select
            v-if="multiple == true"
            v-model="role"
            multiple
            placeholder="请选择角色"
            :dic="rolesOptions"
            :props="roleProps"
          ></avue-select>
          <avue-select
            v-if="multiple == false"
            v-model="role[0]"
            placeholder="请选择角色"
            :dic="rolesOptions"
            :props="roleProps"
          ></avue-select>
        </template>
      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import { addObj, delObj, fetchList, putObj } from "@/api/admin/user";
import { deptRoleList } from "@/api/admin/role";
import { fetchTree } from "@/api/admin/dept";
import { tableOption, tableOption2 } from '@/const/crud/admin/user';
import { mapGetters } from "vuex";

export default {
  name: "table_user",
  data() {
    return {
      option: tableOption,
      option2: tableOption2,
      treeDeptData: [],
      checkedKeys: [],
      roleProps: {
        label: "roleName",
        value: 'roleId'
      },
      defaultProps: {
        label: "name",
        value: 'id',
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false//是否倒序
      },
      list: [],
      listLoading: true,
      role: [],
      form: {},
      rolesOptions: [],

      levelOne: [],

      multiple: true
    };
  },
  computed: {
    ...mapGetters(["permissions"])
  },
  watch: {
    role() {
      this.form.role = this.role
    }
  },
  created() {
    this.sys_user_add = this.permissions["sys_user_add"];
    this.sys_user_edit = this.permissions["sys_user_edit"];
    this.sys_user_del = this.permissions["sys_user_del"];
    sessionStorage.getItem('px-page') == 1 ? this.multiple = true : this.multiple = false
  },
  methods: {
    getList(page, params) {
      var vm = this;
      this.listLoading = true;
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params)).then(response => {
        if (response.data.data.records.length) {
          response.data.data.records.map(r => {
            if (!r.organizations) {
              r.ids = [];
            } else {
              r.ids = r.organizations.split(',');
            }
            return r;
          })
        }
        this.list = response.data.data.records;
        this.page.total = response.data.data.total
        this.listLoading = false;
      });
    },
    getNodeData(data) {
      deptRoleList().then(response => {
        this.rolesOptions = response.data.data;
      });
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    currentChange(current) {
      this.page.currentPage = current
    },
    handleFilter(param, done) {
      this.page.currentPage = 1
      this.getList(this.page, param);
      done()
    },
    handleRefreshChange() {
      this.getList(this.page)
    },
    handleOpenBefore(show, type) {
      window.boxType = type
      // 查询部门树
      fetchTree().then(response => {
        this.treeDeptData = response.data.data
      })
      // 查询角色列表
      deptRoleList().then(response => {
        this.rolesOptions = response.data.data
      })
      // 若是编辑、查看回显角色名称
        // console.log(type)
      if (['edit', 'view'].includes(type)) {
        this.role = []
        for (let i = 0; i < this.form.roleList.length; i++) {
          this.role[i] = this.form.roleList[i].roleId;
        }
      } else if (type === 'add') {
        // 若是添加角色列表设置为空
        this.role = []
      }
      show();
    },
    handleUpdate(row, index) {
      // console.log(row, '123213')
      this.$refs.crud.rowEdit(row, index);
      this.form.password = undefined
    },
    create(row, done, loading) {
      if (this.multiple == true) {
        this.form.organizations = this.form.ids.join(',');
      }
      addObj(this.form).then(() => {
        this.getList(this.page);
        done();
        this.$notify.success('创建成功')
      }).catch(() => {
        loading();
      });
    },
    update(row, index, done, loading) {
      // this.form.organizations = this.form.ids.join(',');
      if (this.multiple == true) {
        this.form.organizations = this.form.ids.join(',');
      }
      putObj(this.form).then(() => {
        this.getList(this.page);
        done();
        this.$notify.success('修改成功')
      }).catch(() => {
        loading();
      });
    },
    deletes(row) {
      this.$confirm("此操作将永久删除该用户(用户名:" + row.username + "), 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消", type: "warning"
      }
      ).then(() => {
        delObj(row.userId).then(() => {
          this.getList(this.page);
          this.$notify.success('删除成功')
        }).catch(() => {
          this.$notify.error('删除失败')
        });
      });
    },
    goPage(row) {
      console.log(row)
      this.$router.push({ path: '/wel/index' })
    }
  }
};
</script>
